import { defineStore } from 'pinia'
import { VerifyLogin } from '@/service/login'
import localCache from '@/utils/localCache'
import router from '@/router'
import useState from '.'
import { fetchUserInfos, fetchUserRole } from '../service/login'
import { ILoginStore } from './type'
import { mapMenuToRoutes } from '@/utils/mapRouteToMenu'
import globeStore from './globe'

const loginStore = defineStore('login', {
  state: (): ILoginStore => ({
    token: '',
    userInfo: {},
    menuList: []
  }),
  getters: {},
  actions: {
    async loginAction(payload: any) {
      // 实现用户登陆
      const res = await VerifyLogin(payload)
      this.token = res.data.token
      localCache.setCache('token', this.token, false)
      // 获取完整的角色/部门
      const { globeStore } = useState()
      globeStore.getInitialUserData()
      // 请求用户信息
      const res1 = await fetchUserInfos(res.data.id)
      // 查询当前用户能访问那些菜单
      const res2 = await fetchUserRole(res.data.id)
      this.userInfo = res1.data
      console.log(res1.data)
      for (const item in res1.data) {
        res1.data['avatar'] =
          'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      localCache.setCache('userInfo', res1.data)

      this.menuList = res2.data
      localCache.setCache('menuList', res2.data)

      this.addRoutes()
      router.push('/')
    },
    addRoutes() {
      const routes = mapMenuToRoutes(this.menuList)
      for (let route in routes) {
        router.addRoute('main', routes[route])
      }
    },
    changeUserAvatar(payload: any) {
      this.userInfo['avatar'] = payload
    }
  }
})

export function getRefreshRoutesData() {
  const useLoginStore = loginStore()
  const token = localCache.getCache('token', false)
  const userInfo = localCache.getCache('userInfo')
  const menuList = localCache.getCache('menuList')

  if (token) {
    useLoginStore.token = token
    // 获取完整的角色/部门
    globeStore().getInitialUserData()
  }
  if (userInfo && Object.keys(userInfo).length !== 0) {
    useLoginStore.userInfo = userInfo
  }
  if (menuList && menuList.length) {
    useLoginStore.menuList = menuList
    useLoginStore.addRoutes()
  }
}
export default loginStore
